﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;


namespace JsonSerializationWithNewTonSoft.Tools
{
    /// <summary>
    /// http请求辅助工具类
    /// </summary>
    public class HttpHelper:IDisposable
    {
        //Http请求/响应主类
        private HttpClient _httpClient ;
        //接口地址
        private string _baseUrl;
        //请求参数
        private IDictionary<string, string> _parameters;    

        public HttpHelper(string baseUrl,IDictionary<string,string>parameters)
        {
            _baseUrl = baseUrl;            
            _parameters = parameters;
            _httpClient = new HttpClient();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public async Task<string> GetDataAsync()
        {
            //拼接地址： 目标地址？**=**&**=**
            var url = $"{_baseUrl}?{CreateRequestData()}";
            try
            {
                //设置请求方法，及目标地址
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                //设置请求头部
                _httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

                //发送请求获得响应对象response
                HttpResponseMessage response =await _httpClient.SendAsync(request);
                //确保正确返回，非正确返回抛异常
                response.EnsureSuccessStatusCode();
                //异步读取响应对象的内容--json
                string result = await response.Content.ReadAsStringAsync();
                //输出/返回
               // Console.WriteLine(result);
                return result;
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
            
        }
        public async Task<string> PostDataAsync()
        {
          
            try
            {
                if (_baseUrl is null) throw new ArgumentNullException(nameof(_baseUrl));
                if(_parameters is null) throw new ArgumentNullException(nameof(_parameters));
             
                var requestParas = CreateRequestData();
                HttpContent content = new StringContent(requestParas, Encoding.UTF8, "application/x-www-form-urlencoded");            
                HttpResponseMessage response = await _httpClient.PostAsync(_baseUrl,content);

                response.EnsureSuccessStatusCode();
                string result = await response.Content.ReadAsStringAsync();               
                return result;
            }
            catch (Exception ex)
            {

                return ex.Message;
            }

        }

       // 参数字典转换为**=**&**=**形式请求参数字符串
        private string CreateRequestData()
        {
            string requestDatas="";
            foreach (var pKey in _parameters.Keys)
            {
                requestDatas += $"{pKey}={_parameters[pKey]}&";
            }
            if (!string.IsNullOrEmpty(requestDatas)) requestDatas.TrimEnd('&');
            return requestDatas;
        }
    }
}
